package com.xiaobao.controller;

import com.xiaobao.pojo.Result;
import com.xiaobao.pojo.User;
import com.xiaobao.pojo.UserInfo;
import com.xiaobao.service.LoginService;
import com.xiaobao.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

// 登录控制层
@RestController
public class LoginController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    private final LoginService loginService;
    private final UserInfoService userInfoService;

    public LoginController(LoginService loginService, UserInfoService userInfoService) {
        this.loginService = loginService;
        this.userInfoService = userInfoService;
    }

    //登入地址
    @PostMapping("/login")
    public Result<UserInfo> login(@RequestBody User user){
        //读取接收的数据
        log.info("用户名：{}", user.getUserName());
        log.info("密码：{}", user.getPassword());
        //获取全部用户
        User[] users = loginService.getAllUser();
        //判断用户是否存在，如果不存在则返回用户不存在的信息
        for (User user1 : users) {
            if (user1.getUserName().equals(user.getUserName()) && user1.getPassword().equals(user.getPassword())) {
               //输出日志用户某某登入成功
                log.info("用户：{} 登入成功", user.getUserName());
                //将用户ID返回去
                //获取用户详细信息
                UserInfo userInfo = userInfoService.getUserInfo(user1.getId());
                return new Result<>(userInfo);
            }
        }
        //如果用户名或者密码错误返回参数错误
        return new Result<>(HttpStatus.BAD_GATEWAY,"用户名或密码错误");
    }//测试完成
}
